import { sin, cos } from './translate'
function getStyle (style, filter = []) {
  const needUnit = [
    'width',
    'height',
    'top',
    'left',
    'borderWidth',
    'borderRadius',
    "rotate"
  ]

  const result = {}
  Object.keys(style).forEach(key => {
    if (!filter.includes(key)) {
      if (key != 'rotate') {
        result[key] = style[key]
        if (needUnit.includes(key)) {
          result[key] += 'px'
        }
      } else {
        result.transform = key + '(' + style[key] + 'deg)'
      }
    }
  })

  return result
}

function LoadStyle (url) {
  let head = document.getElementsByTagName('head')[0]
  let link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  head.appendChild(link)
}

async function runAnimation ($el, animations = []) {
  const play = (animation) => new Promise(resolve => {
    const { animationTime, value = '', isLoop } = animation
    $el.style.setProperty('--time', animationTime + 's')
    $el.classList.add(value, 'animated', utilsHandle(isLoop))
    const removeAnimation = () => {
      $el.removeEventListener('animationend', removeAnimation)
      $el.removeEventListener('animationcancel', removeAnimation)
      $el.classList.remove(value, 'animated', utilsHandle(isLoop))
      $el.style.removeProperty('--time')
      resolve()
    }

    $el.addEventListener('animationend', removeAnimation)
    $el.addEventListener('animationcancel', removeAnimation)
  })

  for (let i = 0, len = animations.length; i < len; i++) {
    await play(animations[i])
  }
}
// 获取一个组件旋转 rotate 后的样式
function getComponentRotatedStyle (style) {
  style = { ...style }
  if (style.rotate != 0) {
    const newWidth = style.width * cos(style.rotate) + style.height * sin(style.rotate)
    const diffX = (style.width - newWidth) / 2 // 旋转后范围变小是正值，变大是负值
    style.left += diffX
    style.right = style.left + newWidth

    const newHeight = style.height * cos(style.rotate) + style.width * sin(style.rotate)
    const diffY = (newHeight - style.height) / 2 // 始终是正
    style.top -= diffY
    style.bottom = style.top + newHeight

    style.width = newWidth
    style.height = newHeight
  } else {
    style.bottom = style.top + style.height
    style.right = style.left + style.width
  }

  return style
}
export {
  getStyle,
  LoadStyle,
  runAnimation,
  getComponentRotatedStyle,
}
